package com.easyhouse.config;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.InetAddress;
import java.util.List;

@Configuration
@ConfigurationProperties(prefix = "easyhouse.es")
public class ESConfig {
    private List<String> nodes;
    private String clusterName;
    //nodes={"10.9.9.9:9300","10.9.9.8:9300"}
    //构造一个TransportClient对象
    @Bean
    public TransportClient initTransportClient() throws Exception {
        Settings settings = Settings.builder().put("cluster.name",clusterName).build();
        PreBuiltTransportClient client = new PreBuiltTransportClient(settings);
        for (String node : nodes) {
            String host = node.split(":")[0];
            int port = Integer.parseInt(node.split(":")[1]);
            TransportAddress address = new InetSocketTransportAddress(
                    InetAddress.getByName(host),port
            );
            client.addTransportAddress(address);
        }
        return client;
    }
    //private Product product;
    public List<String> getNodes() {
        return nodes;
    }

    public void setNodes(List<String> nodes) {
        this.nodes = nodes;
    }
}
